#pragma once
#include "Mutex.hpp"
#include <iostream>
#include <cstdio>
#include <string>
#include <filesystem> //c++17
#include <unistd.h>
#include <fstream>
#include <memory>
#include <time.h>
#include <sstream>
namespace LogMoudule
{
    // 获取当前时间
    std::string GetCurrentTime()
    {
        time_t time_stamp = ::time(nullptr);
        struct tm curr;
        localtime_r(&time_stamp, &curr);
        char buffer[64];
        snprintf(buffer, sizeof(buffer), "%4d-%02d-%02d %02d:%02d:%02d",
                 curr.tm_year + 1900, curr.tm_mon + 1, curr.tm_mday, curr.tm_hour, curr.tm_min, curr.tm_sec);
        return buffer;
    }
    using namespace MutexMoudle;
    // 构成：1.构建日志字符串 2. 刷新落盘(screen,file)
    // 1.默认路径和默认文件名
    const std::string defaultlogpath = "./log/";
    const std::string defaultlogname = "./log.txt";
    // 2.日志等级
    enum class LogLevel
    {
        DEBUG = 1,
        INFO,
        WARNING,
        ERROR,
        FATAL
    };

    // 3.刷新策略
    class LogStrategy
    {
    public:
        virtual ~LogStrategy() = default;
        virtual void SyncLog(const std::string &message) = 0;
    };

    // 3.1控制台策略
    class ConsoleStrategy : public LogStrategy
    {
    public:
        ConsoleStrategy()
        {
        }
        ~ConsoleStrategy()
        {
        }
        void SyncLog(const std::string &message)
        {
            LockGuard lockguard(_lock);
            std::cout << message << std::endl;
        }

    private:
        Mutex _lock;
    };

    // 3.2 文件策略
    class FileLogStrategy : public LogStrategy
    {
    public:
        FileLogStrategy(const std::string &path = defaultlogpath, const std::string &name = defaultlogname)
            : _path(path), _name(name)
        {
            LockGuard lockguard(_lock);
            // 确认path是否存在
            if (std::filesystem::exists(path))
            {
                return;
            }
            try
            {
                std::filesystem::create_directories(path);
            }
            catch (std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << "\n";
            }
        }
        void SyncLog(const std::string &message)
        {
            LockGuard guard(_lock);
            std::string filepath = _path + _name;
            std::ofstream out(filepath, std::ios::app);
            if (!out.is_open())
            {
                return;
            }
            out << message << "\n";
            out.close();
        }
        ~FileLogStrategy()
        {
        }

    private:
        std::string _path;
        std::string _name;
        Mutex _lock;
    };
    std::string LogLeveltoStr(LogLevel level)
    {
        switch (level)
        {
        case LogLevel::DEBUG:
            return "DEBUG";
        case LogLevel::INFO:
            return "INFO";
        case LogLevel::WARNING:
            return "WARNING";
        case LogLevel::ERROR:
            return "ERROR";
        case LogLevel::FATAL:
            return "FATAL";
        default:
            return "NONE";
        }
    }

    // 日志类:构建日志字符串，根据策略进行刷新
    class Logger
    {
    public:
        Logger()
        {
            _strategy = std::make_shared<ConsoleStrategy>();
        }
        void EnableConsoleLog()
        {
            _strategy = std::make_shared<ConsoleStrategy>();
        }
        void EnableFileLog()
        {
            _strategy = std::make_shared<FileLogStrategy>();
        }
        ~Logger()
        {
        }
        class LogMessage
        {
        public:
            LogMessage(LogLevel level, const std::string &filename, uint32_t line, Logger &logger)
                : _currtime(GetCurrentTime()), _level(level), _pid(::getpid()), _filename(filename), _line(line), _logger(logger)
            {
                std::stringstream ssbuffer;
                ssbuffer << "[" << _currtime << "] " << "[" << LogLeveltoStr(_level) << "] " << "[" << _pid << "] " << "[" << _filename << "] " << "[" << _line << "] " << " - ";
                _loginfo = ssbuffer.str();
            }
            template <typename T>
            LogMessage &operator<<(const T &message)
            {
                std::stringstream ssbuffer;
                ssbuffer << message;
                _loginfo += ssbuffer.str();
                return *this;
            }
            ~LogMessage()
            {
                if (_logger._strategy)
                    _logger._strategy->SyncLog(_loginfo);
            }

        private:
            std::string _currtime; // 当前日志的时间
            LogLevel _level;       // 日志等级
            std::string _filename; // 源文件名称
            uint32_t _line;        // 日志所在的行号
            std::string _loginfo;  // 一条完整的日志记录
            pid_t _pid;            // 进程pid
            Logger &_logger;
        };
        LogMessage operator()(LogLevel level, std::string filename, uint32_t line)
        {
            return LogMessage(level, filename, line, *this);
        }

    private:
        std::shared_ptr<LogStrategy> _strategy;
    };
    Logger logger;
#define LOG(level) logger(level, __FILE__, __LINE__)
#define ENABLE_CONSOLE_LOG() logger.EnableConsoleLog()
#define ENABLE_FILE_LOG() logger.EnableFileLog()
}